package com.fingard.remoting.client;

import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.fingard.FGBiz;


/**执行线程*/
public class TenantClientThread implements Runnable {

	/**作为客户端的设置*/
	private TenantClientSet clientSet;
	
	private ScheduledExecutorService pool;
	
	private TenantClient tenantClient;
	
	public TenantClientThread(){
		clientSet = new TenantClientSet();
		String filePath = FGBiz.DSPHOME+File.separator+"config"+File.separator+"TenantClient.xml";
		try {
			clientSet.loadFromXmlFile(filePath);
		} catch (Exception e) {
			FGBiz.limitMsg.exception("TenantClientServer", e);
		}
		
	}
	
	public void start(){
		if(clientSet.enable){
			pool = Executors.newScheduledThreadPool(1);
			tenantClient = new TenantClient(clientSet);
            pool.scheduleWithFixedDelay(tenantClient, clientSet.hbIntervalSecs+5, clientSet.hbIntervalSecs, TimeUnit.SECONDS);
		}
	}
	
	public boolean isEnable(){
		return clientSet.enable;
	}

	@Override
	public void run() {
		if(clientSet.enable){
			int runCount = 0;
			while(true){
				try {
					runCount++;
					if(runCount == 1){
						tenantClient.dealReq();
					}
					if(runCount==5){
						runCount = 1;
					}
					if(!tenantClient.isConnected()){
						int sleepMilSec = 1000+runCount*1000;
						Thread.sleep(sleepMilSec);
					}
					tenantClient.dealReq();
				} catch (Exception e) {
					FGBiz.limitMsg.exception("TenantClientServer", e);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {
						FGBiz.limitMsg.exception("TenantClientServer.sleep", e);
					}
				}
			}
		}
	}
}
